package cn.itheima.action;

import cn.itcast.crm.domain.Customer;
import cn.itheima.action.common.BaseAction;
import cn.itheima.domain.FixedArea;
import cn.itheima.service.FixedAreaService;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.*;

/**
 * Created by millions on 2017/7/3.
 */
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class FixAreaAction extends BaseAction<FixedArea> {

    @Autowired
    private FixedAreaService fixedAreaService;

    @Action(value = "fixedArea_save",results = {@Result(type = "redirect",location = "./pages/base/fixed_area.html")})
    public String fixAreaSave(){


        fixedAreaService.save(model);

        return SUCCESS;
    }

    @Action(value = "fixedArea_pageQuery",results = {@Result(type = "json")})
    public String pageQuery(){
        Pageable pageable=new PageRequest(page-1,rows);

        Specification<FixedArea> specification = new Specification<FixedArea>() {
            @Override
            public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNotBlank(model.getId())) {
                    Predicate p1 = cb.equal(root.get("id").as(String.class), model.getId());
                    list.add(p1);
                }
                if (StringUtils.isNotBlank(model.getCompany())) {
                    Predicate p2 = cb.like(root.get("company").as(String.class), model.getCompany());
                    list.add(p2);
                }

                return cb.and(list.toArray(new Predicate[0]));
            }
        };

        Page<FixedArea> pageData=fixedAreaService.pageQuery(specification,pageable);

        pushPageDataToValueStack(pageData);
        return SUCCESS;
    }

    @Action(value = "findAssociationCustomer",results = {@Result(type = "json")})
    public String findAssociationCustomer(){

        Collection<? extends Customer> customers = WebClient.create("http://localhost:9002/crm_management/services/customerService/associationfixedareacustomers/" + model.getId())
                .accept(MediaType.APPLICATION_JSON_TYPE).getCollection(Customer.class);

        ActionContext.getContext().getValueStack().push(customers);
        return SUCCESS;
    }


    @Action(value = "findNoAssociationCustomer",results = {@Result(type = "json")})
    public String findNoAssociationCustomer(){

        Collection<? extends Customer> customers = WebClient.create("http://localhost:9002/crm_management/services/customerService/noassociationcustomers")
                .accept(MediaType.APPLICATION_JSON_TYPE).getCollection(Customer.class);

        ActionContext.getContext().getValueStack().push(customers);

        return SUCCESS;
    }

    private String[] customerIds;

    public void setCustomerIds(String[] customerIds) {
        this.customerIds=customerIds;
    }

    /**
     * 提交新的客户关联
     * @return
     */
    @Action(value = "associationCustomersToFixedArea",results = {@Result(type = "redirect", location = "./pages/base/fixed_area.html")})
    public String associationCustomersToFixedArea(){

        String customerIdStr = StringUtils.join(customerIds, ",");
        Response response = WebClient.create("http://localhost:9002/crm_management/services/customerService/associationcustomerstofixedarea?customerIdStr=" + customerIdStr + "&fixedAreaId=" + model.getId())
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .put(null);
        System.out.println(response.getStatus());
        return SUCCESS;
    }


    /**
     * 异步提交关联的customerId
     * @return
     */
    @Action(value = "associationCustomersToFixedAreaAjax",results = {@Result(type = "json")})
    public String associationCustomersToFixedAreaAjax(){

        Map<String,Object> map=new HashMap<>();
        map.put("status",200);
        map.put("data","haha");
        ActionContext.getContext().getValueStack().push(map);

        return SUCCESS;
    }


    private Integer takeTimeId;
    private Integer courierId;

    public void setTakeTimeId(Integer takeTimeId) {
        this.takeTimeId = takeTimeId;
    }

    public void setCourierId(Integer courierId) {
        this.courierId = courierId;
    }

    @Action(value = "associationCourierToFixedArea",results = {@Result(type = "redirect",location = "./pages/base/fixed_area.html")})
    public String associationCourierToFixedArea(){

        fixedAreaService.updateAssociationCourierToFixedArea(courierId,takeTimeId,model.getId());

        return SUCCESS;
    }


}
